package com.cn.scenario.controller;

import com.cn.scenario.util.DateUtils;
import com.cn.scenario.util.rateLimiter.RateLimiterUtil;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Boolean
 * @Date 2023/1/12 15:49
 * @Version 1.0
 */
@RestController
@RequestMapping("/limiter")
public class LimiterController {

    /**
     * tryAcquire尝试获取permit，默认超时时间是0，意思是拿不到就立即返回false
     */
    @RequestMapping("/sayHello")
    public String sayHello() {
        if (RateLimiterUtil.rateLimiter.tryAcquire()) { //  一次拿1个
            System.out.println(DateUtils.getFormatString(DateUtils.DATE_TIME_FORMART));
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            System.out.println("limit");
        }
        return "hello";
    }

    /**
     * acquire拿不到就等待，拿到为止
     */
    @RequestMapping("/sayHi")
    public String sayHi() {
        RateLimiterUtil.rateLimiter.acquire(55); //  一次拿5个
        System.out.println(DateUtils.getFormatString(DateUtils.DATE_TIME_FORMART));
        return "hi";
    }
}
